package com.zondy.mapgis.android.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.zondy.mapgis.android.base.BaseActivity;
import com.zondy.mapgis.android.gpx.GPXParser;
import com.zondy.mapgis.android.gpx.bean.GPX;
import com.zondy.mapgis.android.gpx.bean.Route;
import com.zondy.mapgis.android.gpx.bean.Track;
import com.zondy.mapgis.android.gpx.bean.Waypoint;
import com.zondy.mapgis.android.utils.BitmapUtils;
import com.zondy.mapgis.android.utils.FileOperation;
import com.zondy.mapgis.android.utils.ToolToast;
import com.zondy.mapgis.android.utils.ValueUtil;
import com.zondy.mapgis.android.view.pulltorefresh.PullToRefreshLayout;
import com.zondy.mapgis.android.view.pulltorefresh.PullToRefreshLayout.OnRefreshListener;
import com.zondy.mapgis.explorer.MapApplication;
import com.zondy.mapgis.explorer.R;

public class MyTracksActivity extends BaseActivity implements OnClickListener
{
	public String TAG = this.getClass().getSimpleName();
	public MapActivity mMapActivity = null;
	private String TRACKS_PATH = MapApplication.SystemLibraryPath + "Tracks";

	private TextView mTitle = null;
	private ListView mPullListView = null;

	// 当前文件夹下所有的地图文档
	List<File> mGpxFileLst = new ArrayList<File>();
	//按时间排序后的地图文档
	List<File> mOrderFileLst = new ArrayList<File>();
	

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mytracks_layout);
		//透明状态栏  
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);  
        //透明导航栏  
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

		initView();
		mMapActivity = MapApplication.getApp().getMapActivity();
	}

	/**
	 * 初始化窗体
	 */
	private void initView()
	{
		mTitle = (TextView) findViewById(R.id.title_text);
		mTitle.setText("我的轨迹");
		findViewById(R.id.title_back).setOnClickListener(this);

		mPullListView = (ListView) findViewById(R.id.gpx_lst);
		((PullToRefreshLayout) findViewById(R.id.refresh_view)).setOnRefreshListener(new ResultRefreshListen());

		File rootFile = new File(TRACKS_PATH);
		// 判断地图路径是否存在
		if (rootFile.exists())
		{
			mGpxFileLst = getGPXFiles(getAllFile(rootFile));
			//GPX文件按时间排个序
			mOrderFileLst = FileOperation.orderByDate(mGpxFileLst);
			inflateListView(mOrderFileLst);
		}
		else
		{
			ToolToast.showShort("目前没有采集的记录轨迹，快去采集吧。。。");
		}
		mPullListView.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				String filePath = mOrderFileLst.get(position).getAbsolutePath();
				readGpx(filePath);
				// writeGpx(filePath);
			}
		});

	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.title_back:
			finish();
			break;

		default:
			break;
		}
	}

	
	/**
	 * 根据文件夹填充ListView
	 * 
	 * @param files
	 */
	private void inflateListView(List<File> mapFile)
	{

		List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();

		for (int i = 0; i < mapFile.size(); i++)
		{
			Map<String, Object> listItem = new HashMap<String, Object>();

			listItem.put("icon_map", R.drawable.ico_maptrack);
			
			//获取文件名信息
			String fileName = mapFile.get(i).getName();
			String name = fileName.substring(0, fileName.lastIndexOf("."));
			if(null != name)
			{
				String[] nameTxts = name.split("-");
				if(nameTxts.length > 3)
				{
					listItem.put("stat_name", nameTxts[0]);
					listItem.put("end_name", nameTxts[1]);
					listItem.put("route_length", nameTxts[2]);
					listItem.put("time", nameTxts[3]);
				}
				else
				{
					listItem.put("stat_name", mapFile.get(i).getName());
				}
			}
			

			// 获取文件的最后修改日期
			long modTime = mapFile.get(i).lastModified();
//			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
			System.out.println(dateFormat.format(new Date(modTime)));

			// 添加一个最后修改日期
			listItem.put("file_time", "" + dateFormat.format(new Date(modTime)));

			listItems.add(listItem);
		}

		// 定义一个SimpleAdapter
		MySimpleAdapter adapter = new MySimpleAdapter(getApplicationContext(), listItems, R.layout.mytrack_item, new String[] { "icon_map", "stat_name",
			"end_name", "route_length","time","file_time" }, new int[] { R.id.map_imgv, R.id.start_tv, R.id.end_tv, R.id.route_length_tv, R.id.time_tv, R.id.filetime_tv });

		// 填充数据集
		mPullListView.setAdapter(adapter);
	}

	/**
	 * 重写SimpleAdapter适配器
	 * 
	 * @author fjl
	 * 
	 */
	public class MySimpleAdapter extends SimpleAdapter
	{
		@Override
		public View getView(final int position, View convertView, ViewGroup parent)
		{
			View v = super.getView(position, convertView, parent);
			
			ImageView mapImgv = (ImageView) v.findViewById(R.id.map_imgv);
			mapImgv.setTag(position);
			
			//设置GPx对应轨迹图
			File gpxFile = mGpxFileLst.get(position);
			File[] files = gpxFile.getParentFile().listFiles();
			for(File file : files)
			{
				String fileName = file.getName();
				String preFix = fileName.substring(fileName.lastIndexOf(".") + 1);
				if(preFix.equalsIgnoreCase("png"))
				{
					byte[] bytes = BitmapUtils.readFileToBytes(file.getAbsolutePath());
					Bitmap bitmap = BitmapUtils.Bytes2Bimap(bytes);
					mapImgv.setImageBitmap(bitmap);
				}
			}

			return v;
		}

		public MySimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
		{
			super(context, data, resource, from, to);
		}

	}


	@Override
	public void onBackPressed()
	{
		finish();
		super.onBackPressed();
	}

	
	/**
	 * 读取GPX文件
	 * 
	 * @param url
	 */
	private void readGpx(String filePath)
	{
		GPXParser parser = new GPXParser();

		// 读GPX
		FileInputStream in;
		try
		{
			in = new FileInputStream(filePath);
			GPX gpx = parser.parseGPX(in);
			HashSet<Track> trackSet = gpx.getTracks();

			// Iterator<Route> routeIterator = routeSet.iterator();
			// while (routeIterator.hasNext())
			// {
			// Log.d(TAG, routeIterator.next()+ ":routes");
			// //下面这行代码会导致崩溃，暂时没明白原因（java.util.NoSuchElementException）
			// Route route = (Route)routeIterator.next();
			// }
			if (trackSet != null)
			{
				// 跳转到MapActivivity
				Intent intent = new Intent();
				intent.putExtra("trackset", trackSet);
				MyTracksActivity.this.setResult(Activity.RESULT_OK, intent);
				finish();
			}
			else
			{
				ToolToast.showShort("当前轨迹无记录无效");
			}

		}
		catch (ParserConfigurationException e)
		{
			e.printStackTrace();
		}
		catch (SAXException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 获取当前文件夹下所有文件
	 * 
	 * @param rootFile
	 * @return
	 */
	private List<File> getAllFile(File rootFile)
	{
		// 当前路径下所有文件
		List<File> allFiles = new ArrayList<File>();

		File[] mRootFiles = rootFile.listFiles();
		// 根目录
		for (int i = 0; i < mRootFiles.length; i++)
		{
			if (mRootFiles[i].isFile())
			{
				allFiles.add(mRootFiles[i]);
			}
			else
			{
				//二级目录
				File[] secondFiles = mRootFiles[i].listFiles();
				for(File secondFile : secondFiles)
				{
					if(secondFile.isFile())
					{
						allFiles.add(secondFile);
					}
					else
					{
						//三级目录
					}
				}
			}
					
		}
		return allFiles;
	}
	

	/**
	 * 获取所有的地图文档
	 * 
	 * @param filelst
	 * @return
	 */
	private List<File> getGPXFiles(List<File> filelst)
	{
		List<File> gpxFile = new ArrayList<File>();
		for (int i = 0; i < filelst.size(); i++)
		{
			String fileName = filelst.get(i).getName();
			String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
			if(prefix.equalsIgnoreCase("gpx"))
			{
				gpxFile.add(filelst.get(i));
			}
		}
		return gpxFile;

	}

	/**
	 * 刷新监听
	 * 
	 * @author fjl
	 * 
	 */
	class ResultRefreshListen implements OnRefreshListener
	{
		@Override
		public void onRefresh(PullToRefreshLayout pullToRefreshLayout)
		{
			pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
		}

		@Override
		public void onLoadMore(PullToRefreshLayout pullToRefreshLayout)
		{
			pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
		}

	}
	
	/**
	 * 测试写入
	 * 
	 * @param url
	 */
	private void writeGpx(String url)
	{
		GPXParser parser = new GPXParser();
		// 写GPX
		try
		{
			FileOutputStream out = new FileOutputStream(TRACKS_PATH + "/" + ValueUtil.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss:sss"));
			GPX writeGpx = new GPX();

			Waypoint waypoints1 = new Waypoint();
			waypoints1.setLatitude(114.4);
			waypoints1.setLongitude(30.4);
			waypoints1.setTime(new Date(System.currentTimeMillis()));

			Waypoint waypoints2 = new Waypoint();
			waypoints2.setLatitude(114.2);
			waypoints2.setLongitude(30.2);
			waypoints2.setTime(new Date(System.currentTimeMillis()));
			ArrayList<Waypoint> wayPointsLst = new ArrayList<Waypoint>();

			wayPointsLst.add(waypoints1);
			wayPointsLst.add(waypoints2);

			Route route1 = new Route();
			route1.setName("武汉1");
			route1.setNumber(1);
			route1.setRoutePoints(wayPointsLst);
			route1.setSrc("dada");
			route1.setType("经纬度");

			Route route2 = new Route();
			route2.setName("武汉2");
			route2.setNumber(2);
			route2.setRoutePoints(wayPointsLst);
			route2.setSrc("dada");
			route2.setType("经纬度");

			Track tracks1 = new Track();
			tracks1.setName("track1");
			tracks1.setTrackPoints(wayPointsLst);

			Track tracks2 = new Track();
			tracks2.setName("track2");
			tracks2.setTrackPoints(wayPointsLst);

			HashSet<Route> routeSet = new HashSet<Route>();
			routeSet.add(route2);
			routeSet.add(route1);

			HashSet<Waypoint> wayPointSet = new HashSet<Waypoint>();
			wayPointSet.add(waypoints1);
			wayPointSet.add(waypoints2);

			HashSet<Track> trackSet = new HashSet<Track>();
			trackSet.add(tracks1);
			trackSet.add(tracks2);

			writeGpx.setRoutes(routeSet);
			writeGpx.setWaypoints(wayPointSet);
			writeGpx.setTracks(trackSet);
			parser.writeGPX(writeGpx, out);
			out.flush();
			out.close();
		}
		catch (ParserConfigurationException e1)
		{
			e1.printStackTrace();
		}
		catch (TransformerException e1)
		{
			e1.printStackTrace();
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

	}
}
